package com.cmy.framework_widget

import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView

/**
 * @name:
 *  AutoFitImageView
 * @package:
 *  com.cmy.framework_widget
 * @date:
 *  2023/5/1617:37
 * @author
 *    cmy
 * @description
 *  图片自适应:
 *  当ImageView的宽高设置为match_parent时，图片会根据控件的宽高自适应现实；当ImageView的宽高设置为wrap_content时，图片会根据图片的实际宽高自适应现实。
 */
class AutoFitImageView : AppCompatImageView {

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?,defStyleAttr: Int = 0):super( context, attrs ,defStyleAttr)


    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        drawable?.let {
            // 图片的实际宽高
            val imageWidth = it.intrinsicWidth
            val imageHeight = it.intrinsicHeight

            // 控件的宽度
            val widthSize = MeasureSpec.getSize(widthMeasureSpec)
            val widthMode = MeasureSpec.getMode(widthMeasureSpec)

            // 控件的高度
            val heightSize = MeasureSpec.getSize(heightMeasureSpec)
            val heightMode = MeasureSpec.getMode(heightMeasureSpec)

            //计算宽度
           val width = when (widthMode) {
                MeasureSpec.EXACTLY -> {
                    widthSize
                }
                MeasureSpec.AT_MOST -> {
                    imageWidth.coerceAtMost(widthSize)
                }
                else -> {
                    imageWidth
                }
            }

            //计算高度
            val height = when (heightMode) {
                MeasureSpec.EXACTLY -> {
                    heightSize
                }
                MeasureSpec.AT_MOST -> {
                    imageHeight.coerceAtMost(heightSize)
                }
                else -> {
                    imageHeight
                }
            }

            // 重新设置对应的宽高
            setMeasuredDimension(width, height)
        }?:super.onMeasure(widthMeasureSpec, heightMeasureSpec)

    }


}